package com.share.four.netty.marshalling.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {

	/**
	 * 数据压缩
	 */
	public static byte[] gzip(byte[] data) throws Exception{
		//内存输出流--->不是流，相当于内存，所以不用关闭
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		//压缩流
		GZIPOutputStream gin = new GZIPOutputStream(bout);
		//将数据读取到内存输出流中
		gin.write(data);
		gin.finish();
		gin.close();

		byte[] result = bout.toByteArray();
		return result;

	}


	/**
	 * 解压数据
	 */
	public static byte[] unGzip(byte[] data) throws Exception{
		ByteArrayInputStream bin = new ByteArrayInputStream(data);
		GZIPInputStream gin = new GZIPInputStream(bin);

		ByteArrayOutputStream bout = new ByteArrayOutputStream();

		byte[] arr = new byte[1024];
		int len;
		//将data解压缩到arr中，再将arr写到内存（bout）中
		while ((len = gin.read(arr)) != -1) {
			bout.write(arr, 0, len);
		}

		bin.close();gin.close();
		byte[] resutlt = bout.toByteArray();

		return resutlt;
	}
}
